package com.fingard.dsp.bank.directbank.cdrcb01;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectHelper;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CDRCB01BatPayRec extends CDRCB01Base implements IBatPayRec {
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		return d_BatPayRec(p_req1988);
	}

	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		return d_BatPayRec(p_req9188);
	}

	public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
		
		try {
			CDRCB01Header header = new CDRCB01Header();
			header.tranCode = getBankConfig().getMapValueByKey("useType" + p_reqBat.reqHeader.transType,p_reqBat.useType);
			
			XmlTextWriter xmlWriter = new XmlTextWriter();
			xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
			xmlWriter.writeStartElement("BCDL");
			xmlWriter.writeElementString("CST_FLOW", p_reqBat.reqBatchNO);
			
			if ((p_reqBat.reqHeader.transType.equals("1988"))) {
				xmlWriter.writeElementString("PROTOCOL",
						getBankConfig().getMapValueByKey("PROTOCOL" + p_reqBat.reqHeader.transType, p_reqBat.useType));// 代发协议号
			} else if (p_reqBat.reqHeader.transType.equals("9188")) {
				xmlWriter.writeElementString("PROTOCOL",
						getBankConfig().getMapValueByKey("PROTOCOL" + p_reqBat.reqHeader.transType, p_reqBat.useType));// 代发协议号
			}

			if (header.tranCode.equals("020201")) {
				xmlWriter.writeElementString("FUN_CODE", "11");
			} else if (header.tranCode.equals("020202")) {
				xmlWriter.writeElementString("FUN_CODE", "00");
			} else if (header.tranCode.equals("020204")) {
				xmlWriter.writeElementString("FUN_CODE", "22");
			}
			
			xmlWriter.writeElementString("PAY_MONTH", Format.Date6YearMonth.format(p_reqBat.getPayDateTime()));
			xmlWriter.writeElementString("PAY_ACCT", p_reqBat.ownAct);
			xmlWriter.writeElementString("PAY_NAME", p_reqBat.ownActName);
			xmlWriter.writeElementString("TOTALNUM", p_reqBat.totalNum);
			xmlWriter.writeElementString("TOTALAMT", p_reqBat.totalAmt);
			xmlWriter.writeElementString("TRAN_CRY", convertCurToBank(p_reqBat.ownCur));
			xmlWriter.writeStartElement("LIST");
			
			// 保存emp_id至本地
			String useDB = getBankConfig().getValueAsString("useDB");
			if (StringHelper.hasAnyChar(useDB) && "true".equals(useDB)) {
				// 保存至数据表
				HashMap<String, String> mapSeqNum = new HashMap<String, String>();
				
				int empId = 1;
				while (p_reqBat.readRecord()) {
					xmlWriter.writeStartElement("RECORD");
					xmlWriter.writeElementString("EMP_ID", "" + empId);
					mapSeqNum.put(p_reqBat.readedDetail.askNumber, String.valueOf(empId));
					
					// 记入账号和户名
					String act = "", name = "";
					if (header.tranCode.equals("020204")) {
						act = p_reqBat.readedDetail.payAct;
						name = p_reqBat.readedDetail.payName;
					} else {
						act = p_reqBat.readedDetail.recAct;
						name = p_reqBat.readedDetail.recName;
					}
					xmlWriter.writeElementString("REC_ACC", act);
					xmlWriter.writeElementString("REC_NAME", name);
					xmlWriter.writeElementString("TRAN_AMT", p_reqBat.readedDetail.payAmount);
					xmlWriter.writeElementString("PURPOSE", p_reqBat.readedDetail.useType);
					xmlWriter.writeEndElement();
					
					empId++;
				}
				
				StringBuilder sbLog = new StringBuilder();
				boolean saved = DirectHelper.saveSeqNum(p_reqBat.reqHeader.bankCode, p_reqBat.reqBatchNO, mapSeqNum, sbLog);
				if(!saved){
					throw new Exception(sbLog.toString());
				}
			} else {
				// 保存至本地文件
				String dataDir = this.getDataFileDirectory(p_reqBat.getPayDateTime());
				File fileDir = new File(dataDir);
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				File tmpFile = new File(fileDir, p_reqBat.reqBatchNO);
				if (!tmpFile.exists()) {
					tmpFile.createNewFile();
				} else {
					throw new Exception("交易批次号已经存在");
				}

				StringBuilder fileStr = new StringBuilder();
				int empId = 1;
				while (p_reqBat.readRecord()) {
					xmlWriter.writeStartElement("RECORD");
					xmlWriter.writeElementString("EMP_ID", "" + empId);
					// 记入账号和户名
					String act = "", name = "";
					if (header.tranCode.equals("020204")) {
						act = p_reqBat.readedDetail.payAct;
						name = p_reqBat.readedDetail.payName;
					} else {
						act = p_reqBat.readedDetail.recAct;
						name = p_reqBat.readedDetail.recName;
					}
					xmlWriter.writeElementString("REC_ACC", act);
					xmlWriter.writeElementString("REC_NAME", name);
					xmlWriter.writeElementString("TRAN_AMT", p_reqBat.readedDetail.payAmount);
					xmlWriter.writeElementString("PURPOSE", p_reqBat.readedDetail.useType);
					xmlWriter.writeEndElement();
					fileStr.append(p_reqBat.readedDetail.askNumber + "," + empId++ + "," + act + "," + name + ","
							+ StringHelper.amountMultiply100(p_reqBat.readedDetail.payAmount) + "\r\n");
					FileHelper.writeFile(tmpFile, fileStr.toString(), getCharset());
				}
			}
			
			xmlWriter.writeEndDocument();
			
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), header, "MD5");// 发送银行
			if (tmpStrRet[0].length() == 0) {
				String[] strRet = splitRetToString(tmpStrRet[1]);// 把结果拆分成String数组
				if (strRet[0].equals("00000000")) {
					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(strRet[3], tmpSbMsg);
					if (tmpBkReader != null) {
						if (tmpBkReader.read("/BCDL")) {
							String respInfo = tmpBkReader.readedXElement.getSingleText("RET_MSG");
							String tranStt = tmpBkReader.readedXElement.getSingleText("TRAN_STT");
							
							retAts.respCode = "0";
							retAts.respInfo = respInfo;
							retAts.reqSeqID = tmpBkReader.readedXElement.getSingleText("CST_FLOW");
							retAts.transState = tranStt;
							retAts.payInfoCode = respInfo;
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = "返回报文格式不正确";
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = tmpSbMsg.toString();
					}
				} else {
					retAts.respCode = "0";
					retAts.respInfo = strRet[1];
					retAts.transState = strRet[0] + "+" + strRet[1];
					retAts.reqSeqID = p_reqBat.reqBatchNO;
					retAts.payInfoCode = strRet[0];
				}
			} else if (tmpStrRet[0].equals(ConnState.FAIL)) {
				retAts.respCode = "0";
				retAts.respInfo = tmpStrRet[1];
				retAts.reqSeqID = p_reqBat.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = tmpStrRet[0];
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		} catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.toString();
			e.printStackTrace();
		}
		
		if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
			retAts.reqSeqID = p_reqBat.reqBatchNO;
		}
		
		retAts.writeRetToATS();
		return retAts;
	}

	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
		return d_QryBatPayRec(p_req1998);
	}

	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		return d_QryBatPayRec(p_req9198);
	}

	public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
		
		CDRCB01Header bankHeader = new CDRCB01Header();
		bankHeader.tranCode = "001004";
		
		XmlTextWriter xmlWriter = new XmlTextWriter();
		xmlWriter.autoFormat = false;
		xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
		xmlWriter.writeStartElement("BCDL");
		xmlWriter.writeElementString("CST_FLOW", p_reqQryBat.reqBatchNO);
		xmlWriter.writeElementString("BANK_FLOW", "");
		xmlWriter.writeEndDocument();
		
		try {
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader, "ALL");
			if (tmpStrRet[0].length() == 0) {
				String[] strRet = splitRetToString(tmpStrRet[1]);// 把结果拆分成String数组
				if (strRet[0].equals("00000000") && strRet[1].equals("success")) {
					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(strRet[3], tmpSbMsg);
					if (tmpBkReader != null) {
						HashMap<String, String[]> map = null;
						String tranStt = tmpBkReader.getFirstText("/BCDL/TRAN_STT");

						retAts.respCode = "0";
						retAts.transState = tranStt;
						retAts.reqSeqID = tmpBkReader.getFirstText("/BCDL/CST_FLOW");
						retAts.payInfoCode = retAts.transState;
						String payAcct = tmpBkReader.getFirstText("/BCDL/PAY_ACCT");
						
						HashMap<String, String> mapSeqNum = new HashMap<String, String>();
						String useDB = getBankConfig().getValueAsString("useDB");
						if (StringHelper.hasAnyChar(useDB) && "true".equals(useDB)) {
							mapSeqNum = DirectHelper.getSeqNum(p_reqQryBat.reqHeader.bankCode, p_reqQryBat.reqBatchNO);
						}
						
						while (tmpBkReader.read("/BCDL/LIST/RECORD")) {
							RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
							
							String act = tmpBkReader.readedXElement.getSingleText("REC_ACC");
							String name = tmpBkReader.readedXElement.getSingleText("REC_NAME");
							String emp_id = tmpBkReader.readedXElement.getSingleText("EMP_ID");
							String payAmount = StringHelper.amountMultiply100(tmpBkReader.readedXElement.getSingleText("TRAN_AMT"));
							
							// 与提交信息验证
							if (StringHelper.hasAnyChar(useDB) && "true".equals(useDB)) {
								Iterator<String> iter = mapSeqNum.keySet().iterator();
			                    while (iter.hasNext()) {
			                        String askNumber = iter.next();
			                        if (emp_id.equals(mapSeqNum.get(askNumber))) {
			                        	tmpRetDetail.postScript = askNumber;
			                        }
			                    }
							} else {
								if (map == null) {
									map = readFile(p_reqQryBat);
								}
								String[] values = map.get(emp_id);
								if (map.get(emp_id) == null) {
									throw new Exception("找不到相对应的");
								}
								if (!values[2].equals(act) || !values[3].equals(name) || !values[4].equals(payAmount)) {
									throw new Exception("接受到的信息与提交时保存的信息不对应");
								}
								
								tmpRetDetail.postScript = values[0];
							}
							
							if (p_reqQryBat.reqHeader.transType.equals("1998")) {
								tmpRetDetail.payAct = payAcct;
								tmpRetDetail.recAct = act;
								tmpRetDetail.recName = name;
							} else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
								tmpRetDetail.recAct = payAcct;
								tmpRetDetail.payAct = act;
								tmpRetDetail.payName = name;
							}
							tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("TRAN_AMT");
							tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("PURPOSE");
							tmpRetDetail.result = tranStt + "+" + tmpBkReader.readedXElement.getSingleText("TRAN_STT");
							String remark = tmpBkReader.readedXElement.getSingleText("REMARK");
							tmpRetDetail.memo = remark;
							tmpRetDetail.payInfoCode = remark;
							if (remark.equals("") && tmpBkReader.readedXElement.getSingleText("TRAN_STT").equals("2")) {
								tmpRetDetail.payInfoCode = retAts.respInfo;
							}
							retAts.writeRetDetail(tmpRetDetail);
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = tmpSbMsg.toString();
					}
				} else if (strRet[0].equals("BCDL0100") && strRet[1].equals("无交易记录")) {
					retAts.respCode = "0";
					retAts.respInfo = strRet[1];
					retAts.transState = strRet[0] + "+" + strRet[1];
					retAts.payInfoCode = strRet[0];
					retAts.reqSeqID = p_reqQryBat.reqBatchNO;
					retAts.writeBeforeDetail();
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = strRet[1];
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		} catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.getMessage();
			e.printStackTrace();
		}
		if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
			retAts.reqSeqID = p_reqQryBat.reqBatchNO;
		}
		if (retAts.respCode.equals("-1")) {
			retAts.writeBeforeDetail();
		}
		retAts.writeAfterDetail();
		return retAts;
	}

	/*
	 * 读取批量文件 文件是 流水号,EMP_ID,账号,户名,金额 的形式 每行 \r\n 分割
	 */
	protected HashMap<String, String[]> readFile(ReqQryBatPayRec p_reqQryBat) throws Exception {
		String dataDir = this.getDataFileDirectory(p_reqQryBat.getBgnDateTime());
		File fileDir = new File(dataDir);
		File tmpFile = new File(fileDir, p_reqQryBat.reqBatchNO);
		if (!fileDir.exists() || !tmpFile.exists()) {
			throw new Exception("批次号不存在");
		}
		String fileStr = FileHelper.readToString(tmpFile, getCharset());
		HashMap<String, String[]> map = new HashMap<String, String[]>();
		String records[] = fileStr.split("\r\n");
		for (String record : records) {
			String values[] = record.split(",");
			map.put(values[1], values);
		}
		return map;
	}

}
